package cn.itsource.basic.service.impl;

import cn.itsource.basic.service.ICodeService;
import cn.itsource.hbc.user.contants.UserContants;
import cn.itsource.hbc.user.domain.User;
import cn.itsource.hbc.user.mapper.UserMapper;
import cn.itsource.utils.SendMsgUtis;
import cn.itsource.utils.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CodeServiceImpl implements ICodeService {


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void sendCode(Map<String, String> map) {

        // 生成随机数的验证码
        String code = StrUtils.getRandomString(6);
        // 获取map中传递的电话号码
        String phone = map.get("phone");
//        // 将用户的手机号存储到redis中
//        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
//        // 发送验证码
//        SendMsgUtis.send(phone,"尊敬的用户您的验证码是"+code+"请在5分钟内使用，逾期自动失效");
        // 获取用户的手机号
        if(UserContants.REGISTER_CODE.equals(map.get("codeType"))){

            User user = userMapper.loadByPhone(phone);
            if (user!=null){

                throw new RuntimeException("该用户手机号已被注册，请直接登录");

            }
        }



        // 从redis中取出验证码,格式是code：时间搓
        String codeAndTime = (String) redisTemplate.opsForValue().get(map.get("codeType")+":"+phone);

        if(codeAndTime!=null){
            // 获取验证码时间
          Long Time = Long.valueOf(codeAndTime.split(":")[1]);
            if(System.currentTimeMillis()-Time<60*1000){
                throw new RuntimeException("操作频繁");

            }
            // 赋值code
           code = codeAndTime.split(":")[0];

        }
        redisTemplate.opsForValue().set(map.get("codeType")+":"+phone,code+":"+System.currentTimeMillis(),5,TimeUnit.MINUTES);
        System.out.println("本次验证码是："+code);
    }
}
